package com.yearner.reviewplan.plan;

import com.yearner.reviewplan.common.exception.NormalException;
import com.yearner.reviewplan.common.util.StringUtils;
import com.yearner.reviewplan.plan.commands.CreatePlanCommand;
import com.yearner.reviewplan.plan.commands.FinishPlanCommand;
import com.yearner.reviewplan.plan.commands.SearchPlanCommand;
import com.yearner.reviewplan.plan.commands.UpdatePlanCommand;
import com.yearner.reviewplan.plan.model.Plan;
import com.yearner.reviewplan.plan.model.PlanFactory;
import com.yearner.reviewplan.plan.model.PlanId;
import com.yearner.reviewplan.plan.model.PlanVo;
import com.yearner.reviewplan.user.model.Cycle;
import com.yearner.reviewplan.user.model.UserId;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * Plan "写"模型的门面
 * 作为【领域模型】的调用方,本身不应该包含业务逻辑,业务逻辑交给聚合根
 * 不包含查询，查询请找 Representation(基于数据模型)
 * @author pengyg
 * @since 2019/10/12
 */
@Transactional(rollbackFor = RuntimeException.class)
@Service
public class
PlanApplicationService {
    private final PlanRepository repository;
    private final PlanFactory planFactory;

    public PlanApplicationService(PlanRepository planRepository, PlanFactory planFactory) {
        this.repository = planRepository;
        this.planFactory = planFactory;
    }

    /**
     * 新增plan
     * @param command
     * @return
     */
    public void newPlan(CreatePlanCommand command) {
        Plan plan = planFactory.generator(command);
        repository.save(plan,command.getUserId());
    }

    /**
     * 更新数据
     * @param command
     */
    public void updatePlan(UpdatePlanCommand command) {
        Plan plan = repository.byId(command.getUserId(),command.getPlanId());
        plan.updatePlan(command);
        repository.save(plan);
    }

// finishThisTime() 方法已实现该方法
//    public void changeStage(String id,int stage) {
//        Plan plan = repository.byId(id);
//        plan.changeStage(stage);
//        repository.save(plan);
//    }

    /**
     * 点击完成时的操作，根据command来指定到底是 进入下一阶段，还是维持不变，还是回退一个阶段
     * @param userId 用户id
     * @param command 操作指令
     */
    void finishThisTime(String userId, FinishPlanCommand command) {
        validatePlanId(command.getPlanId());
        Plan plan = repository.byId(userId, command.getPlanId());
        plan.finishThisTime(command.getPoint());
        repository.finish(plan.getPlanId().toString(),plan);
    }

    void deletePlan(String userId, String planId) {
        validatePlanId(planId);
        repository.delete(userId, planId);
    }

    private void validatePlanId(String planId) {
        if (StringUtils.isBlank(planId)) {
            throw new NormalException("planId 不能为空");
        }
    }

    public List<Plan> search(String userId, SearchPlanCommand command) {
        List<Plan> planList = repository.search(userId, command);
        return null;
    }
}
